<?php
namespace app\company\controller;

use app\company\model\NormField as normModel;
use app\company\model\NormCategory as categoryModel;

class Norm extends Base
{
	public function index(){
		$norm  = new normModel;
		$list = $norm->order('sort')->paginate();
		$this->assign('list', $list);
		return $this->fetch();
	}

	public function category(){
		$normCate  = new categoryModel;
		$list = $normCate->order('sort')->paginate();
		$this->assign('list', $list);
		return $this->fetch();
	}
	
	public function add(){
		if (request()->isPost()) {
			$norm  = new normModel;
			$result = $norm->allowField(true)
		    ->data(request()->post(), true)
		    ->save();

		    if($result){
		    	$this->success('添加成功','index');
		    }else{
		    	$this->error('添加失败');
		    }

		}else{
			$normCate  = new categoryModel;
			$cate = $normCate->order('sort')->select();
			if(empty($cate)){
				$this->error('请先添加分类','category_add');
			}
			$this->assign('cate', $cate);
			return $this->fetch();
		}
		
	}

	public function edit($id){
		if (request()->isPost()) {
			
			$norm  = new normModel;
			$result = $norm->isUpdate(true)->save(request()->post());
		    if($result){
		    	$this->success('修改成功','index');
		    }else{
		    	$this->error('修改失败');
		    }

		}else{
			$norm  = new normModel;
			$item =$norm::get($id);
			$normCate  = new categoryModel;
			$cate = $normCate->order('sort')->select();
			if(empty($cate)){
				$this->error('请先添加分类','category_add');
			}
			$this->assign('cate', $cate);
			$this->assign('item',$item);
			return $this->fetch();
		}
	}

	public function delete($id){

		$norm  = new normModel;
		$result = $norm::destroy($id);
		if($result){
			$this->success('删除成功','index');
		}else{
			$this->error('删除失败');
		}
	}

	public function category_add(){
		if (request()->isPost()) {

			$category  = new categoryModel;
			$result = $category->allowField(true)
		    ->data(request()->post(), true)
		    ->save();

		    if($result){
		    	$this->success('添加成功','category');
		    }else{
		    	$this->error('添加失败');
		    }

		}else{
			return $this->fetch();
		}
		
	}

	public function category_edit($id){
		if (request()->isPost()) {
			
			$category  = new categoryModel;
			$result = $category->isUpdate(true)->save(request()->post());
		    if($result){
		    	$this->success('修改成功','category');
		    }else{
		    	$this->error('修改失败');
		    }

		}else{
			$category  = new categoryModel;
			$item =$category::get($id);
			$this->assign('item',$item);
			return $this->fetch();
		}
	}

	public function category_delete($id){

		$category  = new categoryModel;
		$result = $category::destroy($id);
		if($result){
			$this->success('删除成功','category');
		}else{
			$this->error('删除失败');
		}
	}
	
}